import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, Button, ScrollView } from '@tarojs/components';
import { queryFundPoolHistory } from '@/services/api/fund';
import PdsEmpty from '@/components/common/pds_empty';
import { parseDateFromStr } from '@/utils/fomatter';
import './index.scss'

class FundHistoricalNetValue extends Component {

    config = {
        navigationBarTitleText: ''
    }

    state = {
        fundId:'',
        dataList: [],
        refresherTriggered: false,
        skeletonLoading: true,
    }

    $instance = getCurrentInstance()

    componentWillMount() {
        var params:any = this.$instance.router?.params
        console.log(params)
        if (params && params['fundId'].length > 0) {
            this.setState({fundId:params['fundId']},()=>{
                this.requestListData(0)
            })
           
        }
     }
    componentDidMount() { }
    componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() { }
    componentDidShow() { }
    componentDidHide() { }
    componentDidCatchError() { }
    componentDidNotFound() { }


    //自定义下拉刷新被触发
    onRefresherRefresh(e) {
        this.setState({ refresherTriggered: true })
        console.log(e, '自定义下拉刷新被触发')
        this.requestListData(false);
    }

    // 滚动到底部上拉加载
    scrolltoLower() {
        this.requestListData(true);
    }

    /**
     * 快速滑动不触发onScrollToLower 的bug
     * @param param0 
     */
    onScroll = ({ detail: { scrollTop, scrollHeight } }) => {
        const { screenHeight, } = Taro.getSystemInfoSync()
        if (
            scrollTop + screenHeight + 100 >= scrollHeight
        ) {
            // this.scrolltoLower(); // 手动触发 onScrollToLower
        }
    };

    /**
     * 
     * @param isAdd 
     */
    requestListData(isAdd) {
        const {  dataList,fundId } = this.state;
        var offset = isAdd ? dataList.length : 0;
        var params:any = this.$instance.router?.params
        if (params && params['fundId'].length > 0) {
            queryFundPoolHistory(params['fundId'],offset).then((resp) => {
                if (resp.code === 200) {
                    if (isAdd) {
                        var tempList: any[] = dataList
                        tempList.push(...resp.data)
                        this.setState({ dataList: tempList });
                    } else {
                        this.setState({ dataList: resp.data });
                    }
    
                }
                this.setState({ refresherTriggered: false, skeletonLoading: false })
            });
           
        }
     
    }

    getDayZdf(item) {
        if (Number(item['preTotalNet']) === 0) {
            return "0.00%"
        }
        return ((Number(item['totalNet']) - Number(item['preTotalNet'])) / Number(item['preTotalNet']) * 100).toFixed(2) + '%'
    }

    render() {
        var scrollTop = 0;
        const { dataList, refresherTriggered, skeletonLoading, } = this.state

        return (
            <View className='page'>
                {
                    dataList.length > 0 ?
                        <View className='table-header' >
                            <Text className='header-item col-3'>日期</Text>
                            <Text className='header-item col-2 text-right'>单位净值</Text>
                            <Text className='header-item col-2 text-right'>累计净值</Text>
                            <Text className='header-item col-2 text-right'>日涨幅</Text>
                        </View> : null
                }
                <ScrollView
                    className='scrollview'
                    scrollY
                    scrollWithAnimation
                    refresherEnabled
                    scrollTop={scrollTop}
                    refresherTriggered={refresherTriggered}
                    lowerThreshold={150}
                    onRefresherRefresh={this.onRefresherRefresh.bind(this)} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
                    onScrollToLower={this.scrolltoLower.bind(this)}
                    onScroll={this.onScroll.bind(this)}
                >
                    {
                        dataList.length === 0 ? <PdsEmpty placeholderText='暂无相关数据'></PdsEmpty> : null
                    }
                    {
                        dataList.map((item, index) => {
                            return <View className='table-content-item'>
                                <Text className='table-content-item-item'>{parseDateFromStr(item['initDate'])}</Text>
                                <Text className='table-content-item-item'>{item['unitNet'] ? Number(item['unitNet']).toFixed(4) : '-'}</Text>
                                <Text className='table-content-item-item'>{item['totalNet'] ? Number(item['totalNet']).toFixed(4) : '-'}</Text>
                                <Text className={`table-content-item-item ${Number(item['preTotalNet']) === 0 ? '' : (Number(item['totalNet']) - Number(item['preTotalNet']) > 0) ? 'num-positive-text' : 'num-negative-text'}`}>{this.getDayZdf(item)}</Text>
                            </View>
                        })
                    }
                </ScrollView >

            </View>
        );
    }
}
export default FundHistoricalNetValue;